﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Messaging;
using JustinAngel.Neurons.Framework;
using JustinAngel.Neurons.Framework.Messages;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.SilverlightMediaFramework.Utilities.Extensions;
using Timeline = Microsoft.SilverlightMediaFramework.Core.Timeline;

namespace JustinAngel.Neurons.Pages.VideoPlayer
{
    public partial class VideoPlayerPage : PhoneApplicationPage
    {
        public VideoPlayerPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(VideoPlayerPage_Loaded);

            IoC.Get<IMessenger>().Register<SetVideoPlayerCurrentPlaybackPositionMessage>(this,
                msg => smfPlayer.SeekToPosition(msg.Content));

            
            IoC.Get<IMessenger>().Register<ApplicationDeactivatedMessage>(this, OnApplicationDeactivatedMessage);

            //InitHack();

        }

        private void OnApplicationDeactivatedMessage(ApplicationDeactivatedMessage obj)
        {
            PhoneApplicationService.Current.State["VideoPlayerViewModel.CurrentPlaybackPosition"] = lastPlaybackPosition;
        }

        void VideoPlayerPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= new RoutedEventHandler(VideoPlayerPage_Loaded);
            if (this.DataContext == null)
            {
                var vm = new ViewModelLocator().VideoPlayerViewModel;
                vm.Data = this.Tag;
                this.DataContext = vm;
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
        }

        private TimeSpan? lastPlaybackPosition = null;

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            lastPlaybackPosition = smfPlayer.PlaybackPosition;

            base.OnNavigatedFrom(e);

            smfPlayer.Stop();
            smfPlayer.Playlist.Clear();

            PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Enabled;
        }

        //private void InitHack()
        //{
        //    stopDraggingIn300MilliSeconds.Tick += new EventHandler(stopDraggingIn300MilliSeconds_Tick);
        //    //t.Tick += new EventHandler(t_Tick);

        ////    DispatcherTimer checkEvery300MillisecondsForMismatchesBetweenTimelineValues = new DispatcherTimer()
        ////    {
        ////        Interval = TimeSpan.FromMilliseconds(300)
        ////    };
        ////    checkEvery300MillisecondsForMismatchesBetweenTimelineValues.Tick += new EventHandler(checkEvery300MillisecondsForMismatchesBetweenTimelineValues_Tick);
        ////    checkEvery300MillisecondsForMismatchesBetweenTimelineValues.Start();
        //}


        //void checkEvery300MillisecondsForMismatchesBetweenTimelineValues_Tick(object sender, EventArgs e)
        //{
        //    if (timeline == null) return;
        //    if ((int)timeline.Value * 1000 != (int)GetPlaybackPositionAsPrecentage() * 1000)
        //    {
        //        smfPlayer.SeekToPosition(GetTimelineValueAsTimeSpan());
        //    }
        //}

        ////void t_Tick(object sender, EventArgs e)
        ////{
        ////    UpdateSMFPlayerLocationBasedOnScrollyThinge();
        ////}

        //private Timeline timeline;
        ////private DispatcherTimer t = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(300)};

        //private void TimelineElement_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        //{
        //    timeline = (Timeline) sender;
        //    timeline.Focus();
        //}


        ////    //if (t.IsEnabled
        ////    //    && TimeSpan.FromMilliseconds(timeline.Value) != timeline.PlaybackPosition)
        ////    //{
        ////    //    t.Stop();

        ////    //    t.Start();
        ////    //}
        ////}

        //private TimeSpan GetTimelineValueAsTimeSpan()
        //{
        //    return TimeSpan.FromMilliseconds(timeline.EndPosition.TotalMilliseconds * timeline.Value);
        //}

        //private double GetPlaybackPositionAsPrecentage()
        //{
        //    return smfPlayer.PlaybackPosition.TotalMilliseconds / timeline.EndPosition.TotalMilliseconds;
        //}

        //private Thumb thumb;
        //private void HorizontalThumb_Loaded(object sender, RoutedEventArgs e)
        //{
        //    thumb = (Thumb) sender;
        //    //thumb.DragStarted += new DragStartedEventHandler(thumb_DragStarted);
        //    //thumb.DragDelta += new DragDeltaEventHandler(thumb_DragDelta);
        //}

        //void thumb_DragStarted(object sender, DragStartedEventArgs e)
        //{
        //    if (thumb.IsDragging)
        //    {
        //        thumb.CancelDrag();
        //    }
        //}

        //private DispatcherTimer stopDraggingIn300MilliSeconds = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(300)};

        //private double totalHorizontalChange;
        //void thumb_DragDelta(object sender, DragDeltaEventArgs e)
        //{
        //    if (stopDraggingIn300MilliSeconds.IsEnabled)
        //        stopDraggingIn300MilliSeconds.Stop();

        //    totalHorizontalChange += e.HorizontalChange;

        //    stopDraggingIn300MilliSeconds.Start();
        //}


        //void stopDraggingIn300MilliSeconds_Tick(object sender, EventArgs e)
        //{
        //    Thumb thumb = (Thumb)sender;
        //    if (thumb.IsDragging)
        //    {
        //        thumb.CancelDrag();
        //    }

        //}

        //private void TimelineElement_LostMouseCapture(object sender, MouseEventArgs e)
        //{
        //    //var timeline = (Timeline)sender;
        //    //smfPlayer.SeekToPosition(timeline.PlaybackPosition);
        //}

        //private void surrondRect_MouseLeave(object sender, MouseEventArgs e)
        //{
        //    //var timeline = (Timeline)sender;
        //    //smfPlayer.SeekToPosition(timeline.PlaybackPosition);
        //}

        //private void TimelineElement_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        //{
        //    //e.Handled = true;
        //}


        //public void UpdateSMFPlayerLocationBasedOnScrollyThinge()
        //{
        //    if (timeline.PlaybackPosition != smfPlayer.PlaybackPosition
        //        && timeline.PlaybackPosition.TotalSeconds >= 1)
        //    {
        //        Debug.WriteLine(timeline.PlaybackPosition);
        //        smfPlayer.SeekToPosition(timeline.PlaybackPosition);
        //    }
        //}
    }
}